import { Button, Tree, Modal, Form, Input, message, Breadcrumb } from "antd";
import RichText from "../components/RichTextModule";
import { DownOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import styles from "./index.module.less";
import type { TreeDataNode, TreeProps } from "antd";
import { useRequest } from "ahooks";
import {
	getBookSectionList,
	getBookSectionDetail,
	addBookSection,
	deleteBookSection,
	editBookSection
} from "@/api/modules/bookshelf";
import { SetStateAction, useEffect, useState, useMemo } from "react";
import useUrl from "@/hooks/useUrl";
import Loading from "@/components/Loading";
import { map } from "lodash";
import { ADD_BOOK_TYPE } from "../List/constant";
import cs from "classnames";
import { QRCodeSVG } from "qrcode.react";

const { TreeNode } = Tree;
const SectionModule = () => {
	const { loading: loadingList, runAsync: getSectionList, data: sectionList } = useRequest(getBookSectionList, { manual: true });
	const { query, state } = useUrl();

	const book_id = query.get("book_id");

	const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
	const [addType, setAddType] = useState<number>(ADD_BOOK_TYPE.chapter);
	const [editChapter, setEditChapter] = useState<any>(null);
	const [isLoadingRichContent, setIsLoadingRichContent] = useState<boolean>(false);

	const [selectedKey, setSelectedKey] = useState(""); // 当前选中的节点 key
	const [modalVisible, setModalVisible] = useState(false); // 弹窗显示状态
	const [currentParentKey, setCurrentParentKey] = useState(null); // 当前操作的父节点 key
	const [richTextIsChange, setRichTextIsChange] = useState(false); // 当前富文本是否被修改

	const [form] = Form.useForm();

	const handleGetTreeData = () => {
		getSectionList({ book_id }).then((res: any) => {
			if(res?.data?.length > 0) {
				setSelectedKey(res?.data[0]?.chapter_id);
			}
			const result = map(res?.data, (item: any) => {
				return {
					...item,
					title: item.chapter_title,
					key: item.chapter_id,
					level: ADD_BOOK_TYPE.chapter,
					children: map(item.children, (child: any) => {
						return {
							...child,
							title: child.chapter_title,
							key: child.chapter_id,
							level: ADD_BOOK_TYPE.section,
							children: map(child.children, (grandChild: any) => {
								return {
									...grandChild,
									title: grandChild.chapter_title,
									key: grandChild.chapter_id,
									level: ADD_BOOK_TYPE.page
								};
							})
						};
					})
				};
			});
			setTreeData(result);
		});
	};

	useEffect(() => {
		if (!book_id) return;
		handleGetTreeData();
	}, []);

	// 点击节点获取富文本内容
	const handleSelectNode: TreeProps["onSelect"] = async (selectedKeys: SetStateAction<null>[], { node }: any) => {
		if (richTextIsChange) {
			Modal.confirm({
				title: "提示",
				icon: <ExclamationCircleOutlined />, // 自定义图标
				content: "修改内容尚未保存，是否确认离开？",
				okText: "确认", // 确认按钮文本
				okType: "danger", // 确认按钮样式
				cancelText: "取消", // 取消按钮文本
				onOk() {
					setSelectedKey(selectedKeys[0]);
					setRichTextIsChange(false);
				},
				// onCancel() {
				// 	setSelectedKey(selectedKey);
				// },
				style: {
					top: "50%", // 可以通过设置 top 值来垂直居中
					transform: "translateY(-50%)" // 使用 transform 调整居中
				},
				okButtonProps: {
					style: {
						backgroundColor: "#1890ff", // 自定义按钮背景色
						color: "white", // 自定义文字颜色
						borderRadius: "5px", // 自定义圆角
						borderColor: "#1890ff"
					}
				},
				cancelButtonProps: {
					style: {
						backgroundColor: "#f0f0f0", // 自定义按钮背景色
						color: "#868686", // 自定义文字颜色
						borderRadius: "5px", // 自定义圆角
						borderColor: "#d9d9d9"
					}
				}
			});
			return;
		}
		setSelectedKey(selectedKeys[0]);
	};

	//新增类型（章、节、页）
	type AddBookTypeValue = (typeof ADD_BOOK_TYPE)[keyof typeof ADD_BOOK_TYPE];
	const handleAddSegment = (type: AddBookTypeValue) => {
		if (!book_id) {
			message.warning("请先保存书籍之后，再返回创建书籍内容！");
			return;
		}
		setAddType(type);
		setModalVisible(true);
	};

	const handleEditNode = (item: any, type: AddBookTypeValue) => {
		setEditChapter(item);
		setModalVisible(true);
		setAddType(type);
		form.setFieldsValue({
			name: item.chapter_title,
			listen_url: item.listen_url
		});
	};

	//提交创建（章、节、页）
	const handleSubmit = async () => {
		const values = await form.validateFields();
		if (!values.name.trim()) return;
		const commonAttr = {
			book_id,
			chapter_title: values.name.trim(),
			listen_url: values.listen_url.trim()
		};
		if (!editChapter) {
			addBookSection({
				...commonAttr,
				chapter_desc: "",
				parent_id: currentParentKey || 0,
				chapter_content: ""
			}).then(res => {
				if (`${res.code}` === "1") {
					message.success("创建成功！");
					form.resetFields();
					setModalVisible(false);
					handleGetTreeData();
				}
			});
		} else {
			editBookSection({
				...commonAttr,
				chapter_id: editChapter?.chapter_id,
				chapter_desc: editChapter?.chapter_desc,
				parent_id: editChapter?.parent_id,
				chapter_content: editChapter?.chapter_content
			}).then(res => {
				if (`${res.code}` === "1") {
					message.success("修改成功！");
					setEditChapter(null);
					form.resetFields();
					setModalVisible(false);
					handleGetTreeData();
				}
			});
		}
	};

	const handleCancel = () => {
		setModalVisible(false);
		form.resetFields();
		setEditChapter(null);
	};

	// 渲染树节点
	const renderTreeNodes = (data) =>
		data.map((item) => {
			const isChapter = item.level === 1; // 判断是否是章
			const isSection = item.level === 2; // 判断是否是节
			const isPage = item.level === 3; // 判断是否是页

			return (
				<TreeNode
					title={
						<div className={cs(styles.customTreeNode, isSection && styles.section, isPage && styles.page)}>
							<div className={cs(styles.nodeTitle, isSection && styles.sectionNodeTitle, isPage && styles.pageNodeTitle)}>
								{item.title}
							</div>
							{(isChapter || isSection) && (
								<>
									<PlusOutlined
										style={{ color: "#1677ff" }}
										onClick={e => {
											e.stopPropagation();
											setCurrentParentKey(item.key);
											handleAddSegment(item.level === 1 ? ADD_BOOK_TYPE.section : ADD_BOOK_TYPE.page);
										}}
									/>
									<EditOutlined
										style={{ color: "#1677ff", margin: "0 5px" }}
										onClick={e => {
											e.stopPropagation();
											handleEditNode(item, item.level === 1 ? ADD_BOOK_TYPE.section : ADD_BOOK_TYPE.page);
										}}
									/>
									<DeleteOutlined
										style={{ color: "#1677ff" }}
										onClick={e => {
											e.stopPropagation();
											handleDeleteNode(item.chapter_id);
										}}
									/>
								</>
							)}
							{isPage && (
								<>
									<EditOutlined
										style={{ color: "#1677ff", margin: "0 5px" }}
										onClick={e => {
											e.stopPropagation();
											handleEditNode(item);
										}}
									/>
									<DeleteOutlined
										style={{ color: "#1677ff" }}
										onClick={e => {
											e.stopPropagation();
											handleDeleteNode(item.chapter_id);
										}}
									/>
								</>
							)}
						</div>
					}
					key={item.key}
				>
					{item.children && renderTreeNodes(item.children)}
				</TreeNode>
			);
		});

	// 删除节点
	const handleDeleteNode = (id: number) => {
		Modal.confirm({
			title: "确认删除吗？",
			icon: <ExclamationCircleOutlined />, // 自定义图标
			content: "删除后数据将无法恢复，请谨慎操作！",
			okText: "确认", // 确认按钮文本
			okType: "danger", // 确认按钮样式
			cancelText: "取消", // 取消按钮文本
			onOk() {
				deleteBookSection({
					chapter_id: id
				}).then(res => {
					if (`${res.code}` === "1") {
						message.success("删除成功！");
						handleGetTreeData();
					}
				});
			},
			style: {
				top: "50%", // 可以通过设置 top 值来垂直居中
				transform: "translateY(-50%)" // 使用 transform 调整居中
			},
			onCancel() {
				// 取消删除的逻辑
				message.info("已取消删除");
			},
			okButtonProps: {
				style: {
					backgroundColor: "#1890ff", // 自定义按钮背景色
					color: "white", // 自定义文字颜色
					borderRadius: "5px", // 自定义圆角
					borderColor: "#1890ff"
				}
			},
			cancelButtonProps: {
				style: {
					backgroundColor: "#f0f0f0", // 自定义按钮背景色
					color: "#868686", // 自定义文字颜色
					borderRadius: "5px", // 自定义圆角
					borderColor: "#d9d9d9"
				}
			}
		});
	};

	const modalTitle = () => {
		const typeEnum = [
			{ key: ADD_BOOK_TYPE.chapter, value: "新增一级目录", editValue: "" },
			{ key: ADD_BOOK_TYPE.section, value: "新增二级目录", editValue: "编辑一级目录" },
			{ key: ADD_BOOK_TYPE.page, value: "新增三级目录", editValue: "编辑二级目录" }
		];
		const result = typeEnum.find(item => item.key === addType);
		return !editChapter ? result?.value : result?.editValue;
	};

	const items = useMemo(() => {
		const init = [
			{
				title: "书籍管理",
				href: "/bookshelf/list"
			},
			{
				title: state.book_name,
				href: `/bookshelf/add?book_id=${state.book_id}`
			},
			{
				title: "录入内容",
				href: "",
				className: styles.active
			}
		];

		return init;
	}, []);

	return (
		<div>
			<Loading loading={loadingList || isLoadingRichContent}>
				<div className={styles.sectionContainer}>
					<Breadcrumb className={styles.breadcrumb} separator=">" items={items} />
					<Modal
						title={modalTitle()}
						visible={modalVisible}
						onOk={handleSubmit}
						onCancel={handleCancel}
						okText="提交"
						cancelText="取消"
						centered
					>
						{/* 弹窗内容 */}
						<Form form={form} layout="vertical">
							<Form.Item name="name" label="名称" rules={[{ required: true, message: "请输入名称" }]}>
								<Input placeholder="请输入名称" />
							</Form.Item>
							<Form.Item name="listen_url" label="音频链接">
								<Input placeholder="请输入音频链接" />
							</Form.Item>
						</Form>
					</Modal>
					<div className={styles.sectionTitle}>录入书籍</div>
					<div className={styles.sectionContent}>
						<div className={styles.leftTree}>
							<Button
								type="primary"
								icon={<PlusOutlined />}
								className={styles.btnAddSection}
								onClick={() => {
									setCurrentParentKey(null);
									handleAddSegment(ADD_BOOK_TYPE.chapter);
								}}
							>
								增加一级目录
							</Button>
							<Tree
								defaultExpandAll
								showLine
								className={styles.treeContainer}
								switcherIcon={<DownOutlined />}
								onSelect={handleSelectNode}
								selectedKeys={[selectedKey]}
							>
								{renderTreeNodes(treeData)}
							</Tree>
						</div>
						<div className={styles.richText}>
							<RichText
								name="chapter_content"
								btnStyles={{ padding: "0 24px" }}
								getDataApi={() => getBookSectionDetail({ chapter_id: selectedKey })}
								saveApi={editBookSection}
								chapterId={selectedKey}
								onValueChange={() => setRichTextIsChange(true)}
								onIsLoading={(value: boolean) => setIsLoadingRichContent(value)}
								setRichTextIsChange={setRichTextIsChange}
							/>
						</div>
						<div className={styles.qrCode}>
							<QRCodeSVG
								value={`https://sxzl.onefishx.com?bookId=${book_id}&bookName=${state.book_name}&chapterId=${selectedKey}&from=preview`}
								size={128}
								level="H" // 纠错级别 (L, M, Q, H)
								renderAs="svg" // 也可以是 'canvas'
							/>
							<div className={styles.qrText}>手机扫码预览该章节效果</div>
						</div>
					</div>
				</div>
			</Loading>
		</div>
	);
};

export default SectionModule;
